from database.mysqlhelper import MySqLHelper
from utils import parse_util

db = MySqLHelper()

insert_sql = 'insert into t_user_info (f_user_code,f_user_name,f_prompt_code,f_task_id) VALUES (%s, %s, %s, %s) '
select_sql = 'select f_user_code, f_user_name, f_prompt_code, f_task_id, f_update_time from t_user_info '


class UserInfoDto:
    def __init__(self, user_code, user_name, prompt_code, task_id):
        self.user_code = user_code
        self.user_name = user_name
        self.prompt_code = prompt_code
        self.task_id = task_id
        self.up_time = ''

    def __repr__(self):
        return repr((self.user_code, self.user_name, self.prompt_code, self.task_id))

    def to_tup(self) -> tuple:
        return (self.user_code, self.user_name, self.prompt_code, self.task_id)


# 格式化结果
def format_dto(res):
    if not res:
        return
    return UserInfoDto(str(res[0], encoding="utf-8"), str(res[1], encoding="utf-8")
                       , str(res[2], encoding="utf-8"), parse_util.byte_to_str(res[3]))


def insert(uid: UserInfoDto):
    return db.insertone(insert_sql, uid.to_tup())


def select_one(code, task_id):
    sql = select_sql + ' where f_user_code = %s and f_task_id = %s '
    return format_dto(db.selectone(sql, (code, task_id)))


# 获取一条
def selectone(code):
    # 增加多条
    sql = select_sql + ' where f_user_code = %s '
    return format_one(db.selectone(sql, (code)))


# 获取所有
def selectall():
    return format_res(db.selectall(select_sql))


# 格式化结果
def format_res(res):
    list = []
    for p in res:
        list.append(format_one(p))
    return list


# 格式化结果
def format_one(res):
    if not res:
        return {}
    return {'user_code': str(res[0], encoding="utf-8"), 'user_name': str(res[1], encoding="utf-8"),
            'prompt_code': str(res[2], encoding="utf-8"), 'up_time': res[3]}
